package com.hema.auction.base;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;

import com.hema.auction.R;
import com.hema.auction.utils.Constant;
import com.hema.auction.utils.Utils;

import java.io.File;


/**
 * author by john
 */

public class BasePhotoFragment extends BaseFragment {

    private Uri uri;
    private AlertDialog dialog;
    private boolean isNeedCrop;

    @Override
    protected int getLayout() {
        return 0;
    }

    public void setPhotoNeedCrop(boolean needCrop) {
        isNeedCrop = needCrop;
    }

    protected void showSelectDialog() {
        if (dialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            String[] items = getResources().getStringArray(R.array.photo);
            builder.setItems(items, (dialog1, which) -> {
                if (which == 0) {
                    takePhoto();
                } else {
                    openAlbum();
                }
            });
            dialog = builder.create();
        }
        dialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                case Constant.REQUEST_CODE_TAKE_PHOTO:
                    // 拍照完成
                    File file = new File(Constant.tempPicture);
                    if (file.exists())
                        if (isNeedCrop)
                            startPhotoZoom(Uri.fromFile(file));
                        else
                            selectPhotoResult(Uri.fromFile(file));
                    break;
                case Constant.REQUEST_CODE_SELECT_PICTURE:
                    // 选择照片完成
                    if (data != null) {
                        if (isNeedCrop)
                            startPhotoZoom(data.getData());
                        else
                            selectPhotoResult(data.getData());
                    }
                    break;
                case Constant.REQUEST_CODE_HANDLE_PHOTO:
                    // 裁剪照片完成
                    if (uri != null) {
                        selectPhotoResult(uri);
                    }
                    break;
            }
        }
    }

    protected void selectPhotoResult(Uri uri) {

    }


    /**
     * 检测是否有拍照权限
     */
    protected void takePhoto() {
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA},
                    Constant.REQUEST_CODE_PERMISS_CEMERA);
        } else {
            openCamera();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQUEST_CODE_PERMISS_CEMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openCamera();
                } else {
                    showToastSafe(R.string.no_permission_camera);
                }
                break;
        }

    }

    /**
     * 打开相机
     */
    protected void openCamera() {
        if (Utils.isSdcardExist()) {
            File dir = new File((getActivity().getExternalFilesDir(null).getPath() + Constant.PHOTO_DIR));
            if (!dir.exists()) dir.mkdirs();
            File tempPic = new File(dir, Constant.IMAGE_TEMP_NAME);
            if (tempPic.exists()) tempPic.delete();
            Constant.tempPicture = tempPic.getAbsolutePath();
            try {
                // 拍照
                Intent intent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(
                        MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(tempPic));
                startActivityForResult(
                        intent,
                        Constant.REQUEST_CODE_TAKE_PHOTO);
            } catch (Exception e) {
            }
        } else {
            showToastSafe(R.string.no_sdcard);
        }
    }

    /**
     * 打开相册
     */
    protected void openAlbum() {
        Intent intentPick = new Intent(Intent.ACTION_PICK);
        intentPick.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Constant.IMAGE_UNSPECIFIED);
        startActivityForResult(intentPick, Constant.REQUEST_CODE_SELECT_PICTURE);
    }


    /**
     * 请求裁剪图片
     *
     * @param uri
     */
    protected void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, Constant.IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        int width = Utils.getDeviceWidth(getActivity());
        width = width > 640 ? 640 : width;
        intent.putExtra("outputX", width);
        intent.putExtra("outputY", width);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        File dir = new File(getActivity().getExternalFilesDir(null).getPath() + Constant.PHOTO_DIR);
        if (!dir.exists()) dir.mkdirs();
        File tempPic = new File(dir, Constant.IMAGE_TEMP_NAME);
        this.uri = Uri.fromFile(tempPic);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, this.uri);
        startActivityForResult(intent, Constant.REQUEST_CODE_HANDLE_PHOTO);
    }

}
